﻿using Learun.Util;
using Learun.Util.SqlSugar;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;

namespace Learun.Application.TwoDevelopment.ZZDT_EC
{
    /// <summary>
    /// 版 本 PIT-ADMS V7.0.3 敏捷开发框架
    /// Copyright (c) 2013-2018 Hexagon PPM
    /// 创 建：超级管理员
    /// 日 期：2022-06-21 15:32
    /// 描 述：关联类型表
    /// </summary>
    public class ec_WireTerminalBLL
    {
        ec_WireTerminalService ec_WireTerminalService;
        public ec_WireTerminalBLL()
        {
            ec_WireTerminalService = new ec_WireTerminalService();
        }

        #region 提交数据


        /// <summary>
        /// 保存实体数据（新增、修改）。也包括删除（NeedRemove为True即可）
        /// <param name="keyValue">主键</param>
        /// <summary>
        /// <returns></returns>
        public void SaveConnections(string ProjectId, ref List<ec_WireTerminalEntity> entitys)
        {
            SqlSugarHelper.Db.BeginTran();
            try
            {
                {
                    var tableName = ProjectSugar.TableName<ec_WireTerminalEntity>(ProjectId);
                    var terms = SqlSugarHelper.Db.Queryable<ec_WireTerminalEntity>().AS(tableName).ToList();
                    var delterms = new List<ec_WireTerminalEntity>();
                    var storeTerms = new List<ec_WireTerminalEntity>();
                    entitys.ForEach(x =>
                    {
                        if (x.NeedRemove)
                        {   //删除的
                            var list = terms.Where(y => y.ID == x.ID).ToList();
                            if ((list == null || list.Count == 0) && !string.IsNullOrEmpty(x.Cable_Side.ToString()))
                            {
                                list = terms.Where(y => y.WireID == x.WireID && y.Cable_Side == x.Cable_Side).ToList();
                            }

                            if ((list == null || list.Count == 0) && !string.IsNullOrEmpty(x.TermID.ToString()))
                            {
                                list = terms.Where(y => y.WireID == x.WireID && y.TermID == x.TermID).ToList();
                            }
                            delterms.AddRange(list);
                        }
                        else
                        {
                            if (!string.IsNullOrEmpty(x.ID))
                            {   //修改的
                                var entity = terms.FirstOrDefault(y => y.ID == x.ID);
                                if (entity != null)
                                {
                                    x.UpdateUserID = entity.UpdateUserID;
                                    x.CreateUserID = entity.CreateUserID;
                                    storeTerms.Add(x);
                                }
                            }
                            else
                            {   //新建的
                                var list = terms.Where(y => y.WireID == x.WireID && y.TermID == x.TermID).ToList();
                                delterms.AddRange(list);
                                x.Create();
                                storeTerms.Add(x);
                            }
                        }
                    });

                    #region 对端子、电芯等的一些额外更新
                    var array = entitys.Where(x => !x.NeedRemove && !string.IsNullOrEmpty(x.ID)).ToList();//已有的信息

                    var wireIds = array.Select(x => x.WireID).Distinct().ToList();
                    var setTableName = ProjectSugar.TableName<ec_CableSetEntity>(ProjectId);
                    var wireTableName = ProjectSugar.TableName<ec_CableSetWireEntity>(ProjectId);

                    var wires = SqlSugarHelper.Db.Queryable<ec_CableSetWireEntity>().Where(x => wireIds.Contains(x.WireID)).AS(wireTableName).ToList();
                    var setIds = wires.Select(x => x.CableSetID).Distinct().ToList();
                    var sets = SqlSugarHelper.Db.Queryable<ec_CableSetEntity>().Where(x => setIds.Contains(x.CableSetID)).AS(setTableName).ToList();
                    array.ForEach(x =>
                    {
                        var set = sets.FirstOrDefault(y => y.CableSetID == x.CableSetID); //待会把setid改为ignore属性里去
                        if (set != null)
                        {
                            set.CableSetName = x.CableSetName;
                        }
                        var wire = wires.FirstOrDefault(y => y.WireID == x.WireID);
                        if (wire != null)
                        {
                            wire.Wire_Tag = x.Wire_Tag;
                            wire.Polarity = x.Polarity;
                        }
                    });
                    #endregion
                    SqlSugarHelper.Db.Deleteable(delterms).AS(tableName).ExecuteCommand();
                    SqlSugarHelper.Db.Storageable(storeTerms).As(tableName).ExecuteCommand();
                    SqlSugarHelper.Db.Updateable(sets).AS(setTableName).ExecuteCommand();
                    SqlSugarHelper.Db.Updateable(wires).AS(wireTableName).ExecuteCommand();
                    SqlSugarHelper.Db.BeginTran();
                    return;
                }
                //{
                //    var ec_SetServ = new ec_CableSetService();
                //    var ec_WireServ = new ec_CableSetWireService();
                //    foreach (var conn in entitys)
                //    {
                //        if (conn.NeedRemove)
                //        {
                //            ec_WireTerminalService.DeleteEntity(ProjectId, conn.ID, conn);
                //        }
                //        else
                //        {
                //            ec_WireTerminalService.SaveEntity(ProjectId, conn.ID, conn);
                //            //2023 05 21，顺道更新下cable里的一些信息，如极性啥。避免移除的时候去改。
                //            ec_WireServ.SaveEntityByConnections(ProjectId, conn.WireID, conn.Wire_Tag, conn.Polarity);
                //            ec_SetServ.SaveEntityByConnections(ProjectId, conn.CableSetID, conn.CableSetName);
                //        }
                //    }
                //}
            }
            catch (Exception ex)
            {
                SqlSugarHelper.Db.RollbackTran();
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowBusinessException(ex);
                }
            }
        }

        #endregion

    }
}
